package com.distributer.order.listener;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.distributer.order.db.DynamicDataSourceContextHolder;
import com.distributer.order.db.TargetDataSource;
import com.distributer.order.event.OrderCreateEvent;
import com.distributer.order.event.OrderItemAddFinishedEvent;
import com.distributer.order.model.Order;
import com.distributer.order.model.OrderItem;
import com.distributer.order.service.OrderItemService;

@Component
public class OrderItemListener {

	@Autowired
	private OrderItemService orderItemService;
	
	@Autowired
	private ApplicationContext applicationContext;
	
	@EventListener
	@Async
	@TargetDataSource("order_item")
	public void handOrderItemCreateEvent(OrderCreateEvent orderCreateEvent){
		Order order = orderCreateEvent.getOrder();
		try {
			List<OrderItem> orderItems = order.getOrderItems();
			DynamicDataSourceContextHolder.setDataSourceType("order_item");
			for (OrderItem orderItem : orderItems) {
				orderItemService.addOrderItem(orderItem);
			}
			applicationContext.publishEvent(new OrderItemAddFinishedEvent(order.getOrderNo(), true));
		} catch (Exception e) {
			applicationContext.publishEvent(new OrderItemAddFinishedEvent(order.getOrderNo(), false));
		}
	}
}
